package com.tidc.manage.controller;

import com.tidc.manage.domain.User;
import com.tidc.manage.dto.UserTokenDTO;
import com.tidc.manage.exception.AuthenticationFailureException;
import com.tidc.manage.service.IUserService;
import com.tidc.manage.tool.RestfulVOResultBuilder;
import com.tidc.manage.vo.RestfulVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;

/**
 * <p>
 * 用户前端控制器
 * </p>
 *
 * @author 张朝锋
 * @author 张伟杰
 * @since 2018-09-14
 */
@RestController
@RequestMapping("/manage/users")
@Api(tags = "用户Api")
public class UserController implements RestfulVOResultBuilder {

    @Autowired
    IUserService userService;

    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public RestfulVO<UserTokenDTO> login(@RequestBody User user) throws IOException, AuthenticationFailureException {
        return data(userService.login(user));
    }

    @ApiOperation(value = "用户登出")
    @PreAuthorize(value = "principal.equals(#userId)")
    @GetMapping("/logout/{userId:\\d+}")
    public RestfulVO<Integer> logout(
            @PathVariable String userId,
            @Param("access_token") String accessToken) {
        return data(userService.logout(userId, accessToken));
    }

    @ApiOperation(value = "用户是否存在")
    @GetMapping("/has/{userId:\\d+}")
    public RestfulVO<Boolean> hasStudent(@PathVariable String userId){
        return data(userService.hasUser(userId));
    }

    @ApiOperation("修改用户密码")
    @PreAuthorize(value = "principal.equals(#studentId)")
    @PutMapping("/{studentId:\\d+}")
    public RestfulVO<Integer> updateUserOfStudentForPasswordByStudentId(
            @Valid @PathVariable String studentId,
            @Param("access_token") String accessToken,
            User user) {
        return data(userService.updateUserOfStudentForPasswordByStudentId(studentId, user, accessToken));
    }
}
